let concurrency = 3; // 默认并发数

// 更新并发数
function updateConcurrency() {
    const newConcurrency = parseInt(document.getElementById('concurrency').value);
    if (newConcurrency > 0 && newConcurrency <= 10) {
        concurrency = newConcurrency;
        alert(`并发处理数已设置为: ${concurrency}`);
    } else {
        alert('请输入1-10之间的数字');
    }
}

// 批量运行质控
function runQualityControlBatch() {
    const selectedFiles = Array.from(document.querySelectorAll('input[name="fileCheckbox"]:checked'))
                              .map(checkbox => checkbox.value);
    
    if (selectedFiles.length === 0) {
        alert('请至少选择一个文件');
        return;
    }
    
    if (confirm(`确定要对选中的 ${selectedFiles.length} 个文件进行质控处理吗？`)) {
        // 禁用按钮防止重复点击
        const runBtn = document.querySelector('[onclick="runQualityControlBatch()"]');
        runBtn.disabled = true;
        
        // 分批处理文件
        processFilesInBatches(selectedFiles, concurrency)
            .then(() => {
                alert('所有文件处理完成');
                loadFiles();
                runBtn.disabled = false;
            })
            .catch(error => {
                console.error('处理过程中出现错误:', error);
                alert('处理过程中出现错误: ' + error.message);
                runBtn.disabled = false;
            });
    }
}

// 分批处理文件
async function processFilesInBatches(files, batchSize) {
    const results = [];
    
    for (let i = 0; i < files.length; i += batchSize) {
        const batch = files.slice(i, i + batchSize);
        const batchPromises = batch.map(filename => 
            fetch(`/api/run-quality-control/${filename}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`处理文件 ${filename} 失败: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => ({ filename, success: true, data }))
                .catch(error => ({ filename, success: false, error: error.message }))
        );
        
        const batchResults = await Promise.all(batchPromises);
        results.push(...batchResults);
        
        // 更新进度
        const processed = Math.min(i + batchSize, files.length);
        console.log(`已处理 ${processed}/${files.length} 个文件`);
    }
    
    return results;
}
